<?php
class mdl_member_online extends ujn_model {

	/**
	 * 插入一条在线记录
	 * @return array($mtkey, $tid, $mtstatus);
	 */
	function insert( $mid ) {
		if(! $mid = $this->uint( $mid)){
			return array('', 0, 0, 0);
		}

		$aInfo = array();
		$aInfo['mtkey'] = md5(microtime(true) . $mid . '$#@!^');

		$query = "INSERT INTO $this->tbl_name SET mtkey='{$aInfo['mtkey']}', mid='$mid', mttime=" . NOW . " ON DUPLICATE KEY UPDATE mtkey='{$aInfo['mtkey']}';";
		$this->_db->query( $query );
		if( $this->_db->affectedRows() > 0) { //原先有记录,要查在哪个桌子
			$_mtkey = $aInfo['mtkey'];
			$query = "SELECT mtkey, tid, svid, mtstatus FROM $this->tbl_name WHERE mid='$mid' LIMIT 1";
			$aInfo = $this->_db->getOne( $query, MYSQL_ASSOC);
			
			$aInfo['mtkey'] = $_mtkey;
		}
		return array(
			isset($aInfo['mtkey']) ? $aInfo['mtkey'] : '',
			isset($aInfo['tid']) ? (int)$aInfo['tid'] : 0,
			isset($aInfo['mtstatus']) ? (int)$aInfo['mtstatus'] : 0,
			isset($aInfo['svid']) ? (int)$aInfo['svid'] : 0
		);
	}

	function getMidByMTKey($mtkey) {
		if(empty($mtkey)) return false;

		$_sql = "select * from {$this->tbl_name} where mtkey='$mtkey' limit 1;";
		$data = $this->_db->getOne($_sql);
		return isset($data['mid']) ? $data['mid'] : false;
	}

	/**
	 * 更新在线表时间 $auth:1无限制2只更新不在房间的
	 */
	public function fresh( $mid, $mtkey, $auth=1){
		if( ! $mid = $this->uint( $mid)){
			return false;
		}
		$mtkey = $this->escape( $mtkey);

		$query = "UPDATE $this->tbl_name SET mttime=UNIX_TIMESTAMP() WHERE mid='$mid' AND mtkey='$mtkey' ".($auth==2?" AND tid=0":" ")." LIMIT 1;";
		$this->_db->query( $query);
		return $this->_db->affectedRows();
	}

	public function get( $mid ) {
		if( ! $mid = $this->uint( $mid ) ) {
			return false;
		}
		$query = "SELECT mtkey FROM $this->tbl_name WHERE mid='$mid' LIMIT 1;";
		return $this->_db->getOne( $query, MYSQL_ASSOC );
	}

	// 当前状态,0为大厅,1为旁观,2为游戏中
	public function getAlls() {
		$query = "SELECT mtkey, mtstatus FROM $this->tbl_name;";
		return $this->_db->getAll($query, MYSQL_ASSOC);
	}

	public function clear(){
	    $threeDaysAgo = TODAY - (86400*3);

	    $query = "DELETE FROM {$this->tbl_name} WHERE `mttime` < {$threeDaysAgo} LIMIT 100;";

	    $this->_db->query($query);
	    return $this->_db->affectedRows();
	}

	public function reset($mid) {
		$sql = "update {$this->tbl_name} set `tid`='0' and `mtstatus`='0' where `mid` = '{$mid}' limit 1;";
		$this->_db->query($sql);
		return $this->_db->affectedRows();
	}

	protected function __construct() {
		parent::__construct();
		$this->db_name		= GAME;
		$this->tbl_name		= "`{$this->db_name}`.`" . GAME . "_membertable`"; // zjh_membertable
		$this->_db			= $this->mysql();
	}

    /**
     * 单例模型
     * @return mdl_member_online
     */
	static function getInstance() {
        return parent::getInstance(__CLASS__);
	}
}